package com.ktjiaoyu.crm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.crm.mapper.UserMapper;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.redis.RedisTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("usr_name",user.getUsrName());
        queryWrapper.eq("usr_password",user.getUsrPassword());
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 根据查询条件获取用户列表
     * @param page
     * @param usrName
     * @param roleId
     * @return
     */
    @Cacheable(value = "{userList}",key = "#page.current+'-'+#page.size+'-'+#usrName+'-'+#roleId",condition = "#page.records!=null")
    @Override
    public Page<User> selectUserPages(Page<User> page, String usrName,Long roleId) {

        //条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        if(usrName != null && !"".equals(usrName)){
            queryWrapper.like("usr_name",usrName);
        }
        if(roleId!=null && roleId!=0){
            queryWrapper.eq("usr_role_id",roleId);
        }

        //查询列表时从redis中先找，如果没有再查数据库
//        Object object = redisTemplateUtil.get("userList:"+page.getCurrent()+":"+page.getSize());
//        if(null != object){
//            //redis中有数据，直接返回
//            return (Page<User>)object;
//        }
        //如果Redis中没有缓存用户列表数据，则从数据库中查询
        List<User> userList = userMapper.selectUserPages(page, queryWrapper);
        page.setRecords(userList);
//        //从数据库中查询到数据后，缓存进redis数据库
//        redisTemplateUtil.set("userList:"+page.getCurrent()+":"+page.getSize(),page);
        return page;
    }

    @CacheEvict(value = "{userList}",allEntries = true)   //清除缓存
    @Override
    public int deleteUserById(Long usrId) {

        return userMapper.deleteById(usrId);
    }

    /**
     * 根据用户名查询用户信息
     * @param name
     * @return
     */
    @Override
    public User getUesrByName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("usr_name",name);

        return userMapper.selectOne(queryWrapper);
    }
}
